package org.wangblue.query;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.metrics.Max;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.wangblue.common.Client;

import java.util.Map;

/**
 * @Description: 获取最大值
 * @Author: WangBlue
 * @Create: 2024-10-24 14:18
 * @Version: 1.0
 **/

public class MaxQuery {
    private static final String INDEX_NAME = "user";
    public static void main(String[] args) {
        try (RestHighLevelClient client = Client.getClient()) {
            // 1. 指定索引
            SearchRequest request = new SearchRequest().indices(INDEX_NAME);

            // 2. 构建查询对象
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.aggregation(AggregationBuilders.max("maxAge").field("age"));

            // 3. 设置请求体
            request.source(sourceBuilder);

            // 4. 客户端发送请求， 获取响应对象
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            // 5. 获取获取最大值
            Aggregations aggregations = response.getAggregations();
            if (aggregations != null) {
                Max maxAge = aggregations.get("maxAge");
                System.out.println("最大年龄：" + maxAge.getValue());
            }

            // 6. 输出查询元数据信息
            System.out.println("took::"+response.getTook());
            System.out.println("time_out::"+response.isTimedOut());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
